package com.gzhryc.shared_device.oem.h5.mng.controllers.market;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.TreeUtils;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.TreeResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketProjectApp;
import com.gzhryc.net_marketing.cloud.business.services.MarketProjectAppService;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpace;
import com.gzhryc.net_marketing.cloud.goods.dao.db.Goods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.GoodsType;
import com.gzhryc.net_marketing.cloud.goods.dao.enums.GoodsEnum;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsSpaceService;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsTypeService;
import com.gzhryc.net_marketing.cloud.goods.services.dto.CloudGoodsSearch;
import com.gzhryc.net_marketing.cloud.goods.services.dto.GoodsSearch;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.net_marketing.core.enums.EGoodsState;
import com.gzhryc.net_marketing.core.models.GoodsSpaceItem;
import com.gzhryc.net_marketing.core.models.GoodsTypeItem;
import com.gzhryc.net_marketing.supplier.erp.dao.enums.SupplierGoodsEnum;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class GoodsController {

	static Logger log = Logger.getLogger(GoodsController.class);

	@Route(value = { "/market/project/goods/list.html" })
	public String list(HttpServletRequest request) {
		return "/market/goods/list.html";
	}

	@Route(value = "/market/project/goods/list.data")
	public ListResult<Goods> listData(HttpServletRequest request) {
		ListResult<Goods> result = new ListResult<Goods>(DtoConstants.NULL_DATA,"暂无数据");
		GoodsSearch search = WebUtils.getParameter(request, GoodsSearch.class);
		Integer pageNo = WebUtils.getInteger(request, "page", 1);
		Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
		
		result.getBody().setTotal(GoodsService.self(MarketConstants.JDBC_KEY).countJoinBySearch(search));
		List<Goods> goodsList = GoodsService.self(MarketConstants.JDBC_KEY).findJoinBySearch(search, pageNo, pageLimit);
		if(goodsList != null && goodsList.size() > 0){
			result.setCode(DtoConstants.SUCCESS, null);
			result.getBody().setData(new ArrayList<>());
			String resDomain = PropertyTools.get().getString("marketResDomain");
			for(Goods goods : goodsList){
				//图片路径
				if (StringTools.isNotBlank(goods.getDetailImgs())) {
					String[] detailImgArray = goods.getDetailImgPaths();
					if (detailImgArray != null && detailImgArray.length > 0) {
						for (int i = 0; i < detailImgArray.length; i++) {
							detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
						}
						goods.setDetailImgs(StringUtils.join(detailImgArray, "|"));
					}
				}
				if (StringTools.isNotBlank(goods.getImgs())) {
					String[] imgArray = goods.getImgPaths();
					if (imgArray != null && imgArray.length > 0) {
						for (int i = 0; i < imgArray.length; i++) {
							imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
						}
						goods.setImgs(StringUtils.join(imgArray, "|"));
					}
				}
				goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, goods.getThumbnailImg()));
				result.getBody().getData().add(goods);
			}
		}
		return result;
	}
	
	@Route(value = { "/market/project/goods/select/list.html" })
	public String cloudList(HttpServletRequest request) {
		request.setAttribute("classifyList", EGoodsClassify.values());
		return "/market/goods/select.html";
	}
	
	@Route(value = "/market/project/goods/select/list.data")
	public ListResult<CloudGoods> cloudGoodsListData(HttpServletRequest request) {
		ListResult<CloudGoods> result = new ListResult<CloudGoods>(DtoConstants.NULL_DATA,"暂无数据");
		CloudGoodsSearch search = WebUtils.getParameter(request, CloudGoodsSearch.class);
		search.setState(EGoodsState.PutOnTheShelf.index());
		Integer pageNo = WebUtils.getInteger(request, "page", 1);
		Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
		
		result.getBody().setTotal(CloudGoodsService.self().countBySearch(search));
		List<CloudGoods> goodsList = CloudGoodsService.self().findBySearch(search, pageNo, pageLimit);
		if(goodsList != null && goodsList.size() > 0){
			result.setCode(DtoConstants.SUCCESS, null);
			result.getBody().setData(new ArrayList<>());
			String resDomain = PropertyTools.get().getString("marketResDomain");
			for(CloudGoods goods : goodsList){
				//图片路径
				if (StringTools.isNotBlank(goods.getDetailImgs())) {
					String[] detailImgArray = goods.getDetailImgPaths();
					if (detailImgArray != null && detailImgArray.length > 0) {
						for (int i = 0; i < detailImgArray.length; i++) {
							detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
						}
						goods.setDetailImgs(StringUtils.join(detailImgArray, "|"));
					}
				}
				if (StringTools.isNotBlank(goods.getImgs())) {
					String[] imgArray = goods.getImgPaths();
					if (imgArray != null && imgArray.length > 0) {
						for (int i = 0; i < imgArray.length; i++) {
							imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
						}
						goods.setImgs(StringUtils.join(imgArray, "|"));
					}
				}
				goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, goods.getThumbnailImg()));
				result.getBody().getData().add(goods);
			}
		}
		return result;
	}
	
	@Route(value = { "/market/project/goods/add.html" })
	public String add(HttpServletRequest request) {
        String resDomain = PropertyTools.get().getString("marketResDomain");
        String resToken = PropertyTools.get().getString("marketResToken");
        String resId = PropertyTools.get().getString("marketResId");
        
        ResourceAPIServer resAPISer = new ResourceAPIServer();
        resAPISer.initial(resDomain, resToken, resId);
        request.setAttribute("marketResDomain", resDomain);
        request.setAttribute("marketResToken",ResourceAPIServer.self().buildTransferToken());
		
	    request.setAttribute("classifyList", EGoodsClassify.values());
		return "/market/goods/edit2.html";
	}

	@Route(value = { "/market/project/goods/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增商品失败");
        Goods goods = WebUtils.getParameter(request, Goods.class);
        if (goods != null && StringUtils.isNotBlank(goods.getName())) {
            Double payMoneyStr = WebUtils.getDouble(request,"payMoneyStr");
            if(payMoneyStr == null) {
                result.setMsg("请填写零售价格");
                return result;
            }
            
            String typeCodes = WebUtils.getString(request,"types");
            if(StringUtils.isBlank(typeCodes)){
                result.setMsg("请填写商品类型");
                return result;
            }
            
            if(goods.getProjectId() == null) {
            	result.setMsg("请填写商品所属商城项目");
                return result;
            }
            
            MarketProjectApp project = MarketProjectAppService.self().getById(goods.getProjectId());
            if(project == null) {
            	result.setMsg("未找到商城项目");
                return result;
            }

            String[] codes = typeCodes.split(",");
            List<GoodsType> goodsTypeList = GoodsTypeService.self().findByCodes(codes);
            if(goodsTypeList != null && goodsTypeList.size() > 0 && goodsTypeList.size() == codes.length) {
            	 goods.setTypeCodes(typeCodes);
            	 String names = "";
            	 for(GoodsType goodsType : goodsTypeList) {
            		 names = names + "," + goodsType.getName();
            	 }
                 goods.setTypeNames(names.substring(1));
                 goods.setClassify(goodsTypeList.get(0).getClassify());
            }else{
                result.setMsg("填写的商品类型有误");
                return result;
            }

            goods.setProjectId(project.getId());
            goods.setAppType(project.getAppType());
            goods.setAppId(project.getAppId());
            goods.setPayMoney(NumberTools.changeMoney(payMoneyStr));
            goods.setSourceType(GoodsEnum.SourceType.Shelf.index());
            
            try {
                if (GoodsService.self(MarketConstants.JDBC_KEY).add(goods)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
	
    @Route(value = { "/market/project/goods/update.html" })
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        Goods goods = GoodsService.self(MarketConstants.JDBC_KEY).getJoinById(id);
        if(goods != null) {
        	String resDomain = PropertyTools.get().getString("resDomain");
            String resToken = PropertyTools.get().getString("resToken");
            String resId = PropertyTools.get().getString("resId");

            if(StringUtils.isNotBlank(goods.getTypeCodes())) {
                String[] codes = goods.getTypeCodes().split(",");
                request.setAttribute("types", codes);
            }
            
            if(GoodsEnum.SourceType.Shelf.index().equals(goods.getSourceType())) {
            	 WebUtils.setAttribute(request, goods);
            	
            	 ResourceAPIServer resAPISer = new ResourceAPIServer();
                 resAPISer.initial(resDomain, resToken, resId);
                 request.setAttribute("marketResDomain", resDomain);
                 request.setAttribute("marketResToken",ResourceAPIServer.self().buildTransferToken());
                 
                 request.setAttribute("stateList", SupplierGoodsEnum.State.values());
                 request.setAttribute("classifyList", EGoodsClassify.values());
                 return "/market/goods/edit2.html";
            }else {
            	//图片路径
    			if (StringTools.isNotBlank(goods.getDetailImgs())) {
    				String[] detailImgArray = goods.getDetailImgPaths();
    				if (detailImgArray != null && detailImgArray.length > 0) {
    					for (int i = 0; i < detailImgArray.length; i++) {
    						detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
    					}
    					goods.setDetailImgs(StringUtils.join(detailImgArray, "|"));
    				}
    			}
    			if (StringTools.isNotBlank(goods.getImgs())) {
    				String[] imgArray = goods.getImgPaths();
    				if (imgArray != null && imgArray.length > 0) {
    					for (int i = 0; i < imgArray.length; i++) {
    						imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
    					}
    					goods.setImgs(StringUtils.join(imgArray, "|"));
    				}
    			}
    			goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, goods.getThumbnailImg()));
    			WebUtils.setAttribute(request, goods);
            }
        }
        return "/market/goods/edit.html";
    }

    @Route(value = { "/market/project/goods/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改商品失败");
        Goods goods = WebUtils.getParameter(request, Goods.class);
        if (goods != null && StringUtils.isNotBlank(goods.getName())) {
        	if(GoodsEnum.SourceType.Shelf.index().equals(goods.getSourceType())) {
	            Double payMoneyStr = WebUtils.getDouble(request,"payMoneyStr");
	            if(payMoneyStr == null) {
	                result.setMsg("请填写零售价格");
	                return result;
	            }
	            String typeCodes = WebUtils.getString(request,"types");
	            if(StringUtils.isBlank(typeCodes)){
	                result.setMsg("请填写商品类型");
	                return result;
	            }
	            
	            String[] codes = typeCodes.split(",");
	            List<GoodsType> goodsTypeList = GoodsTypeService.self().findByCodes(codes);
	            if(goodsTypeList != null && goodsTypeList.size() > 0 && goodsTypeList.size() == codes.length) {
	            	 goods.setTypeCodes(typeCodes);
	            	 String names = "";
	            	 for(GoodsType goodsType : goodsTypeList) {
	            		 names = names + "," + goodsType.getName();
	            	 }
	                 goods.setTypeNames(names.substring(1));
	                 goods.setClassify(goodsTypeList.get(0).getClassify());
	            }else{
	                result.setMsg("填写的商品类型有误");
	                return result;
	            }
	            
	            goods.setPayMoney(NumberTools.changeMoney(payMoneyStr));
	            try {
	                if (GoodsService.self(MarketConstants.JDBC_KEY).updateNotNull(goods)) {
	                    result.setCode(DtoConstants.SUCCESS, null);
	                }
	            } catch (LogicException e) {
	                result.setMsg(e.getMessage());
	            }
        	}else {
        		try {
    				if(goods.getTeamCount() != null && goods.getTeamCount() > 0){
    					if(goods.getTeamCount() < 2) {
    						result.setMsg("至少需要两人进行团拼");
    						return result;
    					}
    					if(goods.getTeamMinute() == null || goods.getTeamMinute() < 30){
    						result.setMsg("组图时长必须30分钟以上");
    						return result;
    					}
    					Double teamPayMoney = WebUtils.getDouble(request, "teamPayMoneyStr");
    					if (teamPayMoney != null) {
    						goods.setTeamPayMoney(NumberTools.changeMoney(teamPayMoney));
    					}else{
    						result.setMsg("请填写拼团价格");
    						return result;
    					}
    				}else {
    					goods.setTeamCount(0);
    					goods.setTeamPayMoney(0);
    					goods.setTeamMinute(30);
    				}

    				Double payMoney = WebUtils.getDouble(request, "payMoneyStr");
    				if (payMoney != null && payMoney > 0) {
    					goods.setPayMoney(NumberTools.changeMoney(payMoney));
    				}else if(goods.getTeamCount() <= 0){
    					result.setMsg("请填写零售价格");
    					return result;
    				}
    				if (GoodsService.self(MarketConstants.JDBC_KEY).updateNotNull(goods)) {
    					result.setCode(DtoConstants.SUCCESS, null);
    				}
    			} catch (LogicException e) {
    				result.setMsg(e.getMessage());
    			}
        	}
        }
        return result;
    }
	
	@Route(value = { "/market/project/cloud/goods/add.html" })
	public String addCloudGoods(HttpServletRequest request) {
		String cid = WebUtils.getString(request, "cid");
		CloudGoods cloudGoods = CloudGoodsService.self().getById(cid);
		if(cloudGoods != null) {
			String resDomain = PropertyTools.get().getString("marketResDomain");
			
			Goods goods = new Goods();
			goods.setCode(cloudGoods.getId());
			goods.setSupplierId(cloudGoods.getSupplierId());
			goods.setSupplierName(cloudGoods.getSupplierName());
			goods.setName(cloudGoods.getName());
			goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, cloudGoods.getThumbnailImg()));
			goods.setClassify(cloudGoods.getClassify());
			goods.setTypeCodes(cloudGoods.getTypeCodes());
			goods.setTypeNames(cloudGoods.getTypeNames());
			goods.setImgs(cloudGoods.getImgs());
			goods.setDetailImgs(cloudGoods.getDetailImgs());
			goods.setLabels(cloudGoods.getLabels());
			goods.setPayMoney(cloudGoods.getPayMoney());
			WebUtils.setAttribute(request, goods);
		}
		return "/market/goods/edit.html";
	}

	@Route(value = { "/market/project/cloud/goods/add.do" })
	public AjaxResult doAddCloudGoods(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增商品失败");
		Double payMoneyStr = WebUtils.getDouble(request,"payMoneyStr");
		if(payMoneyStr == null) {
			result.setMsg("请填写零售价格");
			return result;
		}
		
		String code = WebUtils.getString(request, "code");
		CloudGoods cloudGoods = CloudGoodsService.self().getById(code);
		if(cloudGoods != null) {
			Goods goods = new Goods();
			goods.setCode(cloudGoods.getId());
			goods.setSupplierId(cloudGoods.getSupplierId());
			goods.setSupplierName(cloudGoods.getSupplierName());
			goods.setName(cloudGoods.getName());
			goods.setThumbnailImg(cloudGoods.getThumbnailImg());
			goods.setClassify(cloudGoods.getClassify());
			goods.setTypeCodes(cloudGoods.getTypeCodes());
			goods.setTypeNames(cloudGoods.getTypeNames());
			goods.setImgs(cloudGoods.getImgs());
			goods.setDetailImgs(cloudGoods.getDetailImgs());
			goods.setLabels(cloudGoods.getLabels());
			goods.setSourceType(GoodsEnum.SourceType.Supply.index());
			goods.setPayMoney(NumberTools.changeMoney(payMoneyStr));
			
			List<GoodsSpaceItem> spaceItemList = new ArrayList<GoodsSpaceItem>();
			
			List<CloudGoodsSpace> cloudGoodsSpaceList = CloudGoodsSpaceService.self().findPutByGoodsId(code);
			if(cloudGoodsSpaceList != null && cloudGoodsSpaceList.size() > 0) {
				for(CloudGoodsSpace cloudGoodsSpace : cloudGoodsSpaceList) {
					GoodsSpaceItem spaceItem = new GoodsSpaceItem();
					spaceItem.setId(cloudGoodsSpace.getId());
					spaceItem.setName(cloudGoodsSpace.getName());
					spaceItem.setThumbnailImg(cloudGoodsSpace.getThumbnailImg());
					spaceItem.setStockNum(cloudGoodsSpace.getStockNum());
					spaceItem.setState(cloudGoodsSpace.getState());
					spaceItemList.add(spaceItem);
				}
			}
			
			try {
				if (GoodsService.self(MarketConstants.JDBC_KEY).add(goods,spaceItemList)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = { "/market/project/goods/info.html" })
	public String info(HttpServletRequest request) {
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			Goods goods = GoodsService.self(MarketConstants.JDBC_KEY).getById(id);
			if (goods != null) {
				String resDomain = PropertyTools.get().getString("marketResDomain");
				//图片路径
				if (StringTools.isNotBlank(goods.getDetailImgs())) {
					String[] detailImgArray = goods.getDetailImgPaths();
					if (detailImgArray != null && detailImgArray.length > 0) {
						for (int i = 0; i < detailImgArray.length; i++) {
							detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
						}
						goods.setDetailImgs(StringUtils.join(detailImgArray, "|"));
					}
				}
				if (StringTools.isNotBlank(goods.getImgs())) {
					String[] imgArray = goods.getImgPaths();
					if (imgArray != null && imgArray.length > 0) {
						for (int i = 0; i < imgArray.length; i++) {
							imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
						}
						goods.setImgs(StringUtils.join(imgArray, "|"));
					}
				}
				goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, goods.getThumbnailImg()));

				WebUtils.setAttribute(request, goods);
			}
		}
		return "/business/goods/info.html";
	}

	@Route(value = { "/market/project/goods/up.do" })
	public AjaxResult doUp(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "上架商品失败");
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			try {
				if (GoodsService.self(MarketConstants.JDBC_KEY).upGoods(id)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = { "/market/project/goods/down.do" })
	public AjaxResult doDown(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "下架商品失败");
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			try {
				if (GoodsService.self(MarketConstants.JDBC_KEY).downGoods(id)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}

	@Route(value = { "/market/project/goods/del.do" })
	public AjaxResult doDel(HttpServletRequest request) {
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除商品失败");
		Long id = WebUtils.getLong(request, "id");
		if (id != null) {
			try {
				if (GoodsService.self(MarketConstants.JDBC_KEY).deleteById(id)) {
					result.setCode(DtoConstants.SUCCESS, null);
				}
			} catch (LogicException e) {
				result.setMsg(e.getMessage());
			}
		}
		return result;
	}
	
	@Route("/market/goodsType/tree/select.data")
    public TreeResult<GoodsTypeItem> select(HttpServletRequest request, HttpServletResponse response){
        TreeResult<GoodsTypeItem> result = new TreeResult<GoodsTypeItem>(DtoConstants.SUCCESS);
        List<GoodsType> data = GoodsTypeService.self().findAllUsable();
        if(data != null && data.size() > 0){
            List<GoodsTypeItem> items = TreeUtils.byTree(data, new GoodsTypeService.TreeConvertListen());
            result.getBody().setData(items);
        }
        return result;
    }

}
